<?php

namespace app\h5api\controller;

// 公共类
use Firebase\JWT\JWT as JWTUtil;
use think\Controller;
use think\exception\HttpException;
use think\facade\Config;
use think\facade\Request;

class Base extends Controller
{
	public $_userid = 0;
	public $_openid = '';
    public $limit = 10;

    public function __construct()
    {
//		echo $this->createjwt(['time'=>time(),'user_id'=>323,'nick_name'=>111,'type'=>'online']);die;
        parent::__construct();
		header('Content-Type: text/html;charset=utf-8');
		header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
		header('Access-Control-Allow-Methods:GET,POST,OPTIONS,PUT,DELETE,PATCH'); // 允许请求的类型
		header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
		header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); //

        $this->limit = input('limit',10);
        // 设置允许自定义请求头的字段
		$this->checkToken();
    }

	protected function checkToken()
	{
		$controller = Request()->controller(); //获取控制器名
		$action = Request()->action(); //获取方法名
		$path = $controller.'/'.$action;
		//获取不需要token的页面数组
		$excepts = config::pull('NoTokenApi');
		//循环判断本页面是否需要在这个数组里面
		$isExcept = in_array(strtolower($path),$excepts);
		if (!$isExcept){
			$this->verifyJwt();
		}
	}

	/**
	 * 验证token
	 * &#64;return \think\response\Json
	 */
	public function verifyJwt()
	{
		$token = Request::instance()->header('token');
        if(!$token){
			throw new \think\exception\HttpException(-2, 'token error');
		}
		$key = md5(config::get('token.key')); //jwt的签发密钥，验证token的时候需要用到
		try{
			$jwtAuth = json_encode(JWTUtil::decode($token,$key,['HS256']));
			$authInfo = json_decode($jwtAuth,true);
			if (empty($authInfo['user_id'])){
				throw new \think\exception\HttpException(-2, 'user error');
			}
//			if (empty($authInfo['openid'])){
//				throw new \think\exception\HttpException(-2, 'wechat error');
//			}
			if(empty($authInfo['exp']) || $authInfo['exp'] < time()){
                throw new \think\exception\HttpException(-2, '登录过期');
			}
		}catch (\Exception $e){
			throw new \think\exception\HttpException(-2, $e->getMessage());
		}

		$this->_userid = $authInfo['user_id'];

	}

    // 返回身份数据
    function GetUserInfo()
    {
        $UserModel = new \app\common\model\User();
		$user = $UserModel->field('*')->where(['user_id'=>$this->_userid])->find();
        if(!empty($user)){
            $user = $user->toArray();
        }
        return $user;
    }
}
